<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Services\SampleService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

/**
 * @OA\Tag(
 *     name="welink相关",
 * )
 */
class WeLinkController extends BaseController
{

    /**
     * @OA\Post(
     *     path="/api/welink/login",
     *     tags={"welink相关"},
     *     description="免密登录",
     *     @OA\RequestBody(
     *        @OA\MediaType(
     *            mediaType="application/json",
     *            @OA\Schema(ref="#/components/schemas/LoginRequest"),
     *        )
     *     ),
     *     @OA\Response(
     *          response=200,
     *          description="successful operation",
     *          @OA\JsonContent(ref="#/components/schemas/LoginResponse")
     *      )
     *  )
     */
    public function login(Request $request)
    {
        $code = $request->input('code');
//        $code = '85FA6DB973C88B5DBBD6398E16BC3B9C2C3D3E8EFF9E73584B48EA90BEEB9EA96AF06911B8C5C5D4BCD8BBAA04F666C0';
        $accessToken = Cache::get('access_token', 0);
        if ($accessToken == 0) {
            $ticketsRes = Http::withHeaders([
                'Content-Type' => 'application/json',
            ])->post('https://open.welink.huaweicloud.com/api/auth/v2/tickets', [
                'client_id' => '20240410155710745159965',
                'client_secret' => '68967e8c-d8b1-4e37-ba1d-8072af854498',
            ]);
            $accessToken = $ticketsRes->json('access_token');
            $expiresIn = $ticketsRes->json('expires_in');
            Cache::put('access_token', $accessToken, $expiresIn);
        }

        $useridRes = Http::withHeaders([
            'x-wlk-Authorization' => $accessToken,
        ])->get('https://open.welink.huaweicloud.com/api/auth/v2/userid', [
            'code' => $code,
        ]);
        $userId = $useridRes->json('userId');

        $simpleRes = Http::withHeaders([
            'Content-Type' => 'application/json',
            'x-wlk-Authorization' => $accessToken,
        ])->post('https://open.welink.huaweicloud.com/api/contact/v2/user/detail', [
            'userId' => $userId,
        ]);

        $userData = $simpleRes->json();
        if ($userData['code'] > 0) {
            $res = [
                'code' => $userData['code'],
                'data' => [],
                'message' => $userData['message'],
                'success' => false
            ];
        } else {
            $user = User::where('user_id', $userId)->first();
            if (!$user) {
                $newUser = new User();
                $newUser->name = $userData['userNameCn'];
                $newUser->email = $userData['userEmail'];
                $newUser->email_verified_at = Carbon::now();
                $newUser->user_id = $userData['userId'];
                $newUser->mobile_number = $userData['mobileNumber'];
                $newUser->avatar = $userData['avatar'];
                $newUser->save();
            }

            $res = [
                'code' => 200,
                'data' => $userData,
                'message' => '数据获取成功',
                'success' => true
            ];
        }

        return response()->json($res);
    }

    /**
     * @OA\Post(
     *     path="/api/welink/index",
     *     tags={"welink相关"},
     *     description="获取概览",
     *     @OA\Response(
     *         response="200",
     *         description="The data"
     *     )
     * )
     */
    public function index(Request $request)
    {
        $res = [
            'code' => '200',
            'data' => [

            ],
            'message' => '数据获取成功',
            'success' => true
        ];
        return response()->json($res);
    }

    /**
     * @OA\Post(
     *     path="/api/welink/getSubscribe",
     *     tags={"welink相关"},
     *     description="获取订阅",
     *     @OA\Response(
     *         response="200",
     *         description="The data"
     *     )
     * )
     */
    public function getSubscribe(Request $request)
    {
        $res = [
            'code' => 200,
            'data' => [
                'allSub' => ['宏观经济分析', '工业经济决策分析', '重点检测']
            ],
            'message' => '数据获取成功',
            'success' => true
        ];
        return response()->json($res);
    }

}
